package com.example.nio.network.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年08月06日 16:24:00
 * @Description
 */
public class ChannelClient {

    public static void main(String[] args) {
       try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8888))){
           Scanner scanner = new Scanner(System.in);
           System.out.println("已连接到服务端！");
           System.out.println("请输入要发送给服务端的内容：");
           String text = scanner.nextLine();

           //直接向通道中写入数据，真舒服
           socketChannel.write(ByteBuffer.wrap(text.getBytes()));

           // 接受服务端的返回结果
           ByteBuffer buffer = ByteBuffer.allocate(128);
           socketChannel.read(buffer);
           buffer.flip();
           System.out.println("收到服务器返回："+new String(buffer.array(), 0, buffer.remaining()));

       }catch (Exception ex){
           ex.printStackTrace();
       }
    }

}
